package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住表Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-12-06
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;


    /**
     * 查询入住表
     * 
     * @param id 入住表主键
     * @return 入住表
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住表列表
     * 
     * @param checkIn 入住表
     * @return 入住表
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住表
     * 
     * @param checkIn 入住表
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住表
     * 
     * @param checkIn 入住表
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住表
     * 
     * @param ids 需要删除的入住表主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住表信息
     * 
     * @param id 入住表主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 申请入住表
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto dto) {
        // 1. 检验老人是否已入住 如果已经入住 则直接返回
         LambdaQueryWrapper<Elder> queryWrapper = Wrappers.lambdaQuery();
         queryWrapper.eq(Elder::getIdCardNo,dto.getCheckInElderDto().getIdCardNo());
         queryWrapper.eq(Elder::getStatus,1);
        Elder elder = elderMapper.selectOne(queryWrapper);
        if(ObjectUtils.isNotNull(elder)){
            throw new RuntimeException("老人已入住,请勿重复入住");
        }
        // 2. 更新床位状态为已入住
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        // 3. 新增或更新老人
        elder = insertOrUpdate(dto.getCheckInElderDto(),bed);
        // 4. 新增签约办理
        insertContract(dto, elder);
        // 5. 新增入住表
        CheckIn checkIn = insertCheckIn(dto.getCheckInConfigDto(), elder, bed, dto.getElderFamilyDtoList());
        // 6. 新增入住配置
        insertCheckInConfig(checkIn.getId(), dto.getCheckInConfigDto());
    }


    /**
     * 新增入住配置
     * @param checkInConfigDto
     */
    private void insertCheckInConfig(Long checkInId, CheckInConfigDto checkInConfigDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto, checkInConfig);
        checkInConfig.setCheckInId(checkInId);
        checkInConfigMapper.insert(checkInConfig);
    }
    /**
     * 方法三：新增入住表
     * @param checkInConfigDto
     * @param elder
     * @param bed
     * @param list
     */
    private CheckIn insertCheckIn(CheckInConfigDto checkInConfigDto, Elder elder, Bed bed, List<ElderFamilyDto> list) {
        CheckIn checkIn = new CheckIn();
        //数据拷贝
        BeanUtils.copyProperties(checkInConfigDto,checkIn);
        //老头id 身份证号
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        //入住床位编号
        checkIn.setBedNumber(bed.getBedNumber());
        //状态
        checkIn.setStatus(0);
        //remark
        checkIn.setRemark(JSONUtil.toJsonStr(list));
        checkIn.setElderName(elder.getName());

        checkInMapper.insertCheckIn(checkIn);//插入入住表
        checkIn.setId(checkIn.getId());//赋值主键id

        return checkIn;
    }

    /**
     * 方法二: 新增签约办理
     * @param dto
     * @param elder
     */
    private void insertContract(CheckInApplyDto dto, Elder elder) {
        Contract contract = new Contract();
        //数据拷贝
        BeanUtils.copyProperties(dto.getCheckInContractDto(),contract);
        //老头id
        contract.setElderId(elder.getId());
        //老头姓名
        contract.setElderName(elder.getName());
//        //状态
//        contract.setStatus(1);
        // 状态、开始时间、结束时间
        // 签约时间小于等于当前时间，合同生效中
        LocalDateTime checkInStartTime = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime checkInEndTime = dto.getCheckInConfigDto().getEndDate();
        Integer status = checkInStartTime.isBefore(LocalDateTime.now()) ? 0 : 1;
        contract.setStatus(status);
        contract.setStartDate(checkInStartTime);
        contract.setEndDate(checkInEndTime);
        //签约时间
        contract.setSignDate(dto.getCheckInContractDto().getSignDate());
        //合同
        String number  = "Ht" + CodeGenerator.generateContractNumber();
        contract.setContractNumber(number);
        //合同地址
        System.out.println(contract);
        contractMapper.insertContract(contract);
    }

    /**
     * 方法一: 新增或更新老人
     * @param dto
     * @param bed
     */
    private Elder insertOrUpdate(CheckInElderDto dto,Bed bed) {
        //封装数据
        Elder elder = new Elder();
        //复制属性
        BeanUtils.copyProperties(dto,elder);
        //设置状态
        elder.setStatus(1);
        //设置床位id 和 编号
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        //设置老头性别
        elder.setSex(Long.valueOf(dto.getSex()));

        //判断是新增还是修改
        LambdaQueryWrapper<Elder> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Elder::getIdCardNo,dto.getIdCardNo())
        .ne(Elder::getStatus,1);
        Elder elderOld = elderMapper.selectOne(queryWrapper);
        if(ObjectUtils.isEmpty(elderOld)){
            //新增
            elderMapper.insert(elder);
        }else{
            //修改
            elderMapper.updateById(elder);
        }
        return elder;
    }
}
